﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using UnityEditor;
using UnityEditor.IMGUI.Controls;
using UnityEngine;

namespace XUBuilder
{
    namespace Editor
    {
        internal class XUBuilderAndroidSetting
        {
            [Serializable]
            public class Item
            {
                public ulong channel { get { return _channel; } }
                [SerializeField] private ulong _channel = 0;

                public ulong package { get { return _package; } }
                [SerializeField] private ulong _package = 0;

                public string gameName { get { return _gameName; } set { _gameName = value; } }
                [SerializeField] private string _gameName = "游戏名称";

                public string packageName { get { return _packageName; } set { _packageName = value; } }
                [SerializeField] private string _packageName = "com.pack.name";

                public string bundleVersion { get { return _bundleVersion; } set { _bundleVersion = value; } }
                [SerializeField] private string _bundleVersion = "1.0.1";

                public uint bundleVersionCode { get { return _bundleVersionCode; } set { _bundleVersionCode = value; } }
                [SerializeField] private uint _bundleVersionCode = 1;

                public string keystoreName { get { return _keystoreName; } set { _keystoreName = value; } }
                [SerializeField] private string _keystoreName = "";

                public string keystorePass { get { return _keystorePass; } set { _keystorePass = value; } }
                [SerializeField] private string _keystorePass = "";

                public string keyaliasName { get { return _keyaliasName; } set { _keyaliasName = value; } }
                [SerializeField] private string _keyaliasName = "";

                public string keyaliasPass { get { return _keyaliasPass; } set { _keyaliasPass = value; } }
                [SerializeField] private string _keyaliasPass = "";

                public bool splitApplicationBinary { get { return _splitApplicationBinary; } set { _splitApplicationBinary = value; } }
                [SerializeField] private bool _splitApplicationBinary = false;

                public string manifestPath { get { return GetMainPath() + "/AndroidManifest.xml"; } }

                public string iconPath { get { return GetPicturePath() + "/icon.png"; } }

                public string splashPath { get { return GetPicturePath() + "/splash.png"; } }

                public bool development { get { return _development; } set { _development = value; } }
                [SerializeField] private bool _development = false;

                public bool connectProfiler { get { return _connectProfiler; } set { _connectProfiler = value; } }
                [SerializeField] private bool _connectProfiler = false;

                public bool deepProfilingSupport { get { return _deepProfilingSupport; } set { _deepProfilingSupport = value; } }
                [SerializeField] private bool _deepProfilingSupport = false;

                public bool dontBuild { get { return _dontBuild; } set { _dontBuild = value; } }
                [SerializeField] private bool _dontBuild = false;

                public Item(ulong channel, ulong package)
                {
                    _channel = channel;
                    _package = package;

                    //创建对应的文件夹
                    XUBuilderUtil.EnsureFolder(GetSourcePath());
                    XUBuilderUtil.EnsureFolder(GetPicturePath());
                    XUBuilderUtil.EnsureFolder(GetKeystorePath());
                    XUBuilderUtil.EnsureFolder(GetMainPath());

                    //创建新证书
                    GenKeystore();
                }

                public void GenKeystore()
                {
                    string keystoreNameTmp = package.ToString();
                    string keyaliasNameTmp = package.ToString();
                    string password = package.ToString();
                    //密码需要6位及以上
                    if (password.Length < 6)
                    {
                        int count = 6 - password.Length;
                        for (int i = 0; i < count; i++)
                        {
                            password += password[password.Length - 1];
                        }
                    }
                    bool result = XUBuilderAndroid.GenKeystore(GetKeystorePath(), keystoreNameTmp, keyaliasNameTmp, password);
                    if (result)
                    {
                        keystoreName = keystoreNameTmp;
                        keystorePass = password;
                        keyaliasName = keyaliasNameTmp;
                        keyaliasPass = password;
                    }
                    else
                    {
                        EditorUtility.DisplayDialog("提示", "证书生成失败\n请检查JDK是否有添加到系统环境变量\n可以在 cmd 中测试下 keytool 命令", "确定");
                    }
                }

                public string GetSourcePath()
                {
                    return XUBuilderAndroid.GetInputPath() + "/" + package;
                }

                public string GetPicturePath()
                {
                    return GetSourcePath() + "/picture";
                }

                public string GetKeystorePath()
                {
                    return GetSourcePath() + "/keystore";
                }

                public string GetMainPath()
                {
                    return GetSourcePath() + "/main";
                }
            }

            //=============================================================================================================

            [SerializeField]
            private List<Item> allItem = new List<Item>();

            public Item GetItem(ulong channel, ulong package)
            {
                foreach (var item in allItem)
                {
                    if (item.channel == channel && item.package == package)
                    {
                        return item;
                    }
                }
                return null;
            }

            //=============================================================================================================

            public static XUBuilderAndroidSetting LoadOrCreate()
            {
                XUBuilderUtil.EnsureFolder(XUBuilderAndroid.GetCommonPath());

                XUBuilderAndroidSetting instance;

                string jsonPath = XUBuilderAndroid.GetInputPath() + "/builder.json";
                if (File.Exists(jsonPath))
                {
                    string jsonText = File.ReadAllText(jsonPath, Encoding.UTF8);
                    instance = JsonUtility.FromJson<XUBuilderAndroidSetting>(jsonText);
                }
                else
                {
                    instance = new XUBuilderAndroidSetting();
                    instance.Save();
                }

                return instance;
            }

            public void Save()
            {
                XUBuilderUtil.EnsureFolder(XUBuilderAndroid.GetCommonPath());

                string jsonPath = XUBuilderAndroid.GetInputPath() + "/builder.json";
                string jsonText = JsonUtility.ToJson(this, true);
                if (File.Exists(jsonPath))
                {
                    string lastText = File.ReadAllText(jsonPath, Encoding.UTF8);
                    if (!jsonText.Equals(lastText))
                    {
                        File.WriteAllText(jsonPath, jsonText, Encoding.UTF8);
                    }
                }
                else
                {
                    if (!Directory.Exists(Path.GetDirectoryName(jsonPath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(jsonPath));
                    }
                    File.WriteAllText(jsonPath, jsonText, Encoding.UTF8);
                }
            }

            //=============================================================================================================

            private ulong channelText;
            private ulong packageText;

            private MultiColumnHeaderState channelTreeMCHState;
            private ChannelTreeView channelTreeView;
            private SearchField channelSearchField;

            private Dictionary<string, KeyValuePair<long, XmlDocument>> manifestFiles = new Dictionary<string, KeyValuePair<long, XmlDocument>>();
            private Dictionary<string, KeyValuePair<long, Texture>> pictureFiles = new Dictionary<string, KeyValuePair<long, Texture>>();

            public void OnGUI(EditorWindow window)
            {
                GUIStyle centeredStyle = new GUIStyle(GUI.skin.GetStyle("Label"));
                centeredStyle.alignment = TextAnchor.UpperCenter;

                GUIStyle titleStyle = new GUIStyle(GUI.skin.GetStyle("Label"));
                titleStyle.alignment = TextAnchor.UpperCenter;
                titleStyle.normal.textColor = Color.green;

                GUILayout.BeginHorizontal();
                GUILayout.FlexibleSpace();
                {
                    GUILayout.Label("渠道号:");
                    channelText = (ulong)EditorGUILayout.LongField((long)channelText);
                    GUILayout.Label("包号:");
                    packageText = (ulong)EditorGUILayout.LongField((long)packageText);
                    if (GUILayout.Button("添加新渠道"))
                    {
                        if (channelText <= 0)
                        {
                            EditorUtility.DisplayDialog("错误", "渠道号不能小于等于0", "确定");
                        }
                        else if (packageText <= 0)
                        {
                            EditorUtility.DisplayDialog("错误", "包号不能小于等于0", "确定");
                        }
                        else
                        {
                            Item item = GetItem(channelText, packageText);
                            if (item != null)
                            {
                                EditorUtility.DisplayDialog("错误", "配置已经存在，不可重复添加", "确定");
                            }
                            else
                            {
                                allItem.Add(new Item(channelText, packageText));
                                channelTreeView = null;
                            }
                        }
                    }
                }
                GUILayout.EndHorizontal();

                GUILayout.BeginHorizontal();
                {
                    GUILayout.BeginVertical("Box", GUILayout.Width(200));
                    {
                        if (channelTreeView == null)
                        {
                            var headerState = ChannelTreeView.CreateDefaultMultiColumnHeaderState();
                            if (MultiColumnHeaderState.CanOverwriteSerializedFields(channelTreeMCHState, headerState))
                            {
                                MultiColumnHeaderState.OverwriteSerializedFields(channelTreeMCHState, headerState);
                            }
                            channelTreeMCHState = headerState;
                            channelTreeView = new ChannelTreeView(new TreeViewState(), channelTreeMCHState, this);
                            channelSearchField = new SearchField();
                            channelSearchField.downOrUpArrowKeyPressed += channelTreeView.SetFocusAndEnsureSelectedItem;
                        }
                        channelTreeView.searchString = channelSearchField.OnToolbarGUI(channelTreeView.searchString);
                        channelTreeView.OnGUI(GUILayoutUtility.GetRect(0, 100000, 0, 100000));
                    }
                    GUILayout.EndVertical();

                    GUILayout.BeginVertical("Box", GUILayout.Width(585), GUILayout.Height(721));
                    {
                        if (channelTreeView != null)
                        {
                            Item selectItem = channelTreeView.GetSelectItem();
                            if (selectItem != null)
                            {
                                EditorGUILayout.LabelField("--------------------------- 基础参数 ---------------------------", titleStyle);
                                GUILayout.Space(3);
                                {
                                    GUILayout.BeginHorizontal();
                                    {
                                        EditorGUILayout.LabelField("渠道号:", GUILayout.Width(40));
                                        EditorGUI.BeginDisabledGroup(true);
                                        EditorGUILayout.TextField(selectItem.channel.ToString());
                                        EditorGUI.EndDisabledGroup();
                                        EditorGUILayout.LabelField("包号:", GUILayout.Width(30));
                                        EditorGUI.BeginDisabledGroup(true);
                                        EditorGUILayout.TextField(selectItem.package.ToString());
                                        EditorGUI.EndDisabledGroup();
                                    }
                                    GUILayout.EndHorizontal();

                                    GUILayout.BeginHorizontal();
                                    {
                                        EditorGUILayout.LabelField("游戏名:", GUILayout.Width(40));
                                        string gameNameText = EditorGUILayout.TextField(selectItem.gameName);
                                        selectItem.gameName = !string.IsNullOrEmpty(gameNameText) ? gameNameText : selectItem.gameName;
                                        EditorGUILayout.LabelField("包名:", GUILayout.Width(30));
                                        string packageNameText = EditorGUILayout.TextField(selectItem.packageName);
                                        selectItem.packageName = !string.IsNullOrEmpty(packageNameText) ? packageNameText : selectItem.packageName;
                                    }
                                    GUILayout.EndHorizontal();

                                    GUILayout.BeginHorizontal();
                                    {
                                        EditorGUILayout.LabelField("bundleVersion:", GUILayout.Width(90));
                                        string bundleVersionText = EditorGUILayout.TextField(selectItem.bundleVersion);
                                        selectItem.bundleVersion = !string.IsNullOrEmpty(bundleVersionText) ? bundleVersionText : selectItem.bundleVersion;
                                        EditorGUILayout.LabelField("bundleVersionCode:", GUILayout.Width(120));
                                        uint bundleVersionCodeText = (uint)EditorGUILayout.LongField(selectItem.bundleVersionCode);
                                        selectItem.bundleVersionCode = bundleVersionCodeText > 0 ? bundleVersionCodeText : selectItem.bundleVersionCode;
                                    }
                                    GUILayout.EndHorizontal();
                                }

                                GUILayout.Space(3);
                                EditorGUILayout.LabelField("--------------------------- 发布设置 ---------------------------", titleStyle);
                                GUILayout.Space(3);
                                {
                                    GUILayout.BeginHorizontal();
                                    {
                                        if (GUILayout.Button("生成证书"))
                                        {
                                            selectItem.GenKeystore();
                                        }
                                    }
                                    GUILayout.EndHorizontal();

                                    GUILayout.BeginHorizontal();
                                    {
                                        EditorGUILayout.LabelField("证书名称:", GUILayout.Width(60));
                                        string keystoreNameText = EditorGUILayout.TextField(selectItem.keystoreName);
                                        selectItem.keystoreName = !string.IsNullOrEmpty(keystoreNameText) ? keystoreNameText : selectItem.keystoreName;
                                        EditorGUILayout.LabelField("证书密码:", GUILayout.Width(60));
                                        string keystorePassText = EditorGUILayout.TextField(selectItem.keystorePass);
                                        selectItem.keystorePass = !string.IsNullOrEmpty(keystorePassText) ? keystorePassText : selectItem.keystorePass;
                                    }
                                    GUILayout.EndHorizontal();

                                    GUILayout.BeginHorizontal();
                                    {
                                        EditorGUILayout.LabelField("别名账号:", GUILayout.Width(60));
                                        string keyaliasNameText = EditorGUILayout.TextField(selectItem.keyaliasName);
                                        selectItem.keyaliasName = !string.IsNullOrEmpty(keyaliasNameText) ? keyaliasNameText : selectItem.keyaliasName;
                                        EditorGUILayout.LabelField("别名密码:", GUILayout.Width(60));
                                        string keyaliasPassText = EditorGUILayout.TextField(selectItem.keyaliasPass);
                                        selectItem.keyaliasPass = !string.IsNullOrEmpty(keyaliasPassText) ? keyaliasPassText : selectItem.keyaliasPass;
                                    }
                                    GUILayout.EndHorizontal();

                                    selectItem.splitApplicationBinary = EditorGUILayout.Toggle("Split Application Binary", selectItem.splitApplicationBinary);
                                }

                                GUILayout.Space(3);
                                EditorGUILayout.LabelField("--------------------------- AndroidManifest.xml ---------------------------", titleStyle);
                                GUILayout.Space(3);
                                {
                                    FileInfo fileInfo = new FileInfo(selectItem.manifestPath);
                                    if (fileInfo.Exists)
                                    {
                                        long lastWriteTime = fileInfo.LastWriteTime.Ticks;
                                        if (!manifestFiles.ContainsKey(fileInfo.FullName))
                                        {
                                            manifestFiles.Add(fileInfo.FullName, new KeyValuePair<long, XmlDocument>(lastWriteTime, new XmlDocument()));
                                            manifestFiles[fileInfo.FullName].Value.Load(fileInfo.FullName);
                                        }
                                        else
                                        {
                                            if (manifestFiles[fileInfo.FullName].Key != lastWriteTime || manifestFiles[fileInfo.FullName].Value == null)
                                            {
                                                manifestFiles[fileInfo.FullName] = new KeyValuePair<long, XmlDocument>(lastWriteTime, new XmlDocument());
                                                manifestFiles[fileInfo.FullName].Value.Load(fileInfo.FullName);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (!manifestFiles.ContainsKey(fileInfo.FullName))
                                        {
                                            manifestFiles.Add(fileInfo.FullName, new KeyValuePair<long, XmlDocument>(0, null));
                                        }
                                        else
                                        {
                                            manifestFiles[fileInfo.FullName] = new KeyValuePair<long, XmlDocument>(0, null);
                                        }
                                    }

                                    int minSdkVersion = 0;
                                    int targetSdkVersion = 0;

                                    XmlDocument manifestXml = manifestFiles[fileInfo.FullName].Value;
                                    if (manifestXml != null)
                                    {
                                        XmlNode xnRoot = manifestXml.SelectSingleNode("manifest");
                                        if (xnRoot != null)
                                        {
                                            XmlNode xnSDK = xnRoot.SelectSingleNode("uses-sdk");
                                            XmlElement xeSDK = (XmlElement)xnSDK;
                                            if (xeSDK != null)
                                            {
                                                minSdkVersion = int.Parse(xeSDK.GetAttribute("android:minSdkVersion"));
                                                targetSdkVersion = int.Parse(xeSDK.GetAttribute("android:targetSdkVersion"));
                                            }
                                        }
                                    }

                                    GUILayout.BeginHorizontal();
                                    {
                                        EditorGUILayout.LabelField("minSdkVersion:", GUILayout.Width(100));
                                        EditorGUI.BeginDisabledGroup(true);
                                        EditorGUILayout.IntField(minSdkVersion);
                                        EditorGUI.EndDisabledGroup();
                                        EditorGUILayout.LabelField("targetSdkVersion:", GUILayout.Width(110));
                                        EditorGUI.BeginDisabledGroup(true);
                                        EditorGUILayout.IntField(targetSdkVersion);
                                        EditorGUI.EndDisabledGroup();
                                    }
                                    GUILayout.EndHorizontal();
                                }

                                GUILayout.Space(3);
                                EditorGUILayout.LabelField("--------------------------- 出包素材 ---------------------------", titleStyle);
                                GUILayout.Space(3);
                                {
                                    GUILayout.BeginHorizontal();
                                    {
                                        List<string> allTexturePath = new List<string>();
                                        allTexturePath.Add(selectItem.iconPath);
                                        allTexturePath.Add(selectItem.splashPath);
                                        foreach (var file in allTexturePath)
                                        {
                                            FileInfo fileInfo = new FileInfo(file);
                                            if (fileInfo.Exists)
                                            {
                                                long lastWriteTime = fileInfo.LastWriteTime.Ticks;
                                                if (!pictureFiles.ContainsKey(file))
                                                {
                                                    pictureFiles.Add(file, new KeyValuePair<long, Texture>(lastWriteTime, new WWW("file://" + file).texture));
                                                }
                                                else
                                                {
                                                    if (pictureFiles[file].Key != lastWriteTime || pictureFiles[file].Value == null)
                                                    {
                                                        pictureFiles[file] = new KeyValuePair<long, Texture>(lastWriteTime, new WWW("file://" + file).texture);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (!pictureFiles.ContainsKey(file))
                                                {
                                                    pictureFiles.Add(file, new KeyValuePair<long, Texture>(0, EditorGUIUtility.FindTexture("console.errorIcon")));
                                                }
                                                else
                                                {
                                                    pictureFiles[file] = new KeyValuePair<long, Texture>(0, EditorGUIUtility.FindTexture("console.errorIcon"));
                                                }
                                            }

                                            Texture texture = pictureFiles[file].Value;
                                            int height = 128;
                                            int width = (int)((height * 1f / texture.height) * texture.width);

                                            GUILayout.BeginVertical("Box", GUILayout.Width(width), GUILayout.Height(height));
                                            {
                                                GUILayout.Box(texture, GUILayout.Width(width), GUILayout.Height(height));
                                                GUILayout.Label(texture.width + " x " + texture.height, centeredStyle);
                                                GUILayout.Label(fileInfo.Name, centeredStyle);
                                                GUILayout.Label(XUBuilderUtil.GetSizeString(fileInfo.Exists ? fileInfo.Length : 0), centeredStyle);
                                            }
                                            GUILayout.EndVertical();
                                        }
                                    }
                                    GUILayout.EndHorizontal();
                                }

                                GUILayout.Space(3);
                                EditorGUILayout.LabelField("--------------------------- 其他设置 ---------------------------", titleStyle);
                                GUILayout.Space(3);
                                {
                                    selectItem.development = EditorGUILayout.Toggle("Development", selectItem.development);
                                    selectItem.connectProfiler = EditorGUILayout.Toggle("ConnectProfiler", selectItem.connectProfiler);
                                    selectItem.deepProfilingSupport = EditorGUILayout.Toggle("DeepProfilingSupport", selectItem.deepProfilingSupport);
                                    GUILayout.Space(10);
                                    selectItem.dontBuild = EditorGUILayout.Toggle(new GUIContent("Dont Build", "只替换Setting和Plugins，不构建apk"), selectItem.dontBuild);
                                }
                            }
                        }
                    }
                    GUILayout.EndVertical();
                }
                GUILayout.EndHorizontal();

                if (channelTreeView != null)
                {
                    Item selectItem = channelTreeView.GetSelectItem();
                    if (selectItem != null)
                    {
                        if (GUI.Button(new Rect(window.position.width - 220, window.position.height - 40, 120, 30), "构建apk"))
                        {
                            if (EditorUtility.DisplayDialog("提示",
                                "检查构建参数" +
                                "\n\n渠道号:" + selectItem.channel +
                                "\n\n包号:" + selectItem.package +
                                "\n\n游戏名:" + selectItem.gameName +
                                "\n\n包名:" + selectItem.packageName,
                                "确定", "取消"))
                            {
                                if (EditorUserBuildSettings.activeBuildTarget != BuildTarget.Android)
                                {
                                    EditorUtility.DisplayDialog("提示", "当前工程不是Android平台", "确定");
                                }
                                else
                                {
                                    XUBuilderAndroid.Build(selectItem);
                                }
                            }
                        }

                        if (GUI.Button(new Rect(window.position.width - 95, window.position.height - 40, 80, 30), "删除"))
                        {
                            if (EditorUtility.DisplayDialog("提示", "确定要删除配置？\n包号:" + selectItem.package + "\n游戏名:" + selectItem.gameName, "确定", "取消"))
                            {
                                allItem.Remove(selectItem);
                                channelTreeView = null;

                                if (Directory.Exists(selectItem.GetSourcePath()))
                                {
                                    if (EditorUtility.DisplayDialog("提示", "是否要清空资源文件夹？\n" + selectItem.GetSourcePath(), "确定", "取消"))
                                    {
                                        XUBuilderUtil.ClearFolder(selectItem.GetSourcePath(), true);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //=============================================================================================================

            private class ChannelTreeView : TreeView
            {
                private TreeViewItem root = new TreeViewItem { id = 0, depth = -1, displayName = "Root" };
                private List<TreeViewItem> allItems = new List<TreeViewItem>();

                private XUBuilderAndroidSetting setting;
                private Dictionary<int, KeyValuePair<ulong, ulong>> allChannel = new Dictionary<int, KeyValuePair<ulong, ulong>>();

                public ChannelTreeView(TreeViewState treeViewState, MultiColumnHeaderState mchs, XUBuilderAndroidSetting setting)
                    : base(treeViewState, new MultiColumnHeader(mchs))
                {
                    this.setting = setting;

                    List<ulong> channels = new List<ulong>();
                    Dictionary<ulong, List<ulong>> packages = new Dictionary<ulong, List<ulong>>();
                    foreach (var item in setting.allItem)
                    {
                        if (!channels.Contains(item.channel))
                        {
                            channels.Add(item.channel);
                        }
                    }
                    channels.Sort();
                    foreach (var channel in channels)
                    {
                        if (!packages.ContainsKey(channel))
                        {
                            packages.Add(channel, new List<ulong>());
                        }
                        foreach (var item in setting.allItem)
                        {
                            if (item.channel == channel)
                            {
                                packages[channel].Add(item.package);
                            }
                        }
                        packages[channel].Sort();
                    }

                    int index = 1;
                    foreach (var channel in packages)
                    {
                        foreach (var package in channel.Value)
                        {
                            TreeViewItem packageItem = new TreeViewItem
                            {
                                id = index++,
                                depth = 0,
                                displayName = package.ToString(),
                                icon = EditorGUIUtility.FindTexture("BuildSettings.Android.Small"),
                            };
                            allChannel.Add(packageItem.id, new KeyValuePair<ulong, ulong>(channel.Key, package));
                            allItems.Add(packageItem);
                        }
                    }

                    showBorder = true;

                    Reload();

                    if (index > 1)
                    {
                        SetSelection(new List<int>() { 1 });
                    }
                }

                protected override TreeViewItem BuildRoot()
                {
                    SetupParentsAndChildrenFromDepths(root, allItems);
                    return root;
                }

                protected override bool CanMultiSelect(TreeViewItem item)
                {
                    return false;
                }

                public Item GetSelectItem()
                {
                    TreeViewItem viewItem = null;
                    foreach (var id in GetSelection())
                    {
                        viewItem = FindItem(id, rootItem);
                    }
                    if (viewItem != null)
                    {
                        if (allChannel.ContainsKey(viewItem.id))
                        {
                            return setting.GetItem(allChannel[viewItem.id].Key, allChannel[viewItem.id].Value);
                        }
                    }
                    return null;
                }

                //=============================================================

                protected override void RowGUI(RowGUIArgs args)
                {
                    for (int i = 0; i < args.GetNumVisibleColumns(); ++i)
                        CellGUI(args.GetCellRect(i), args.item as TreeViewItem, args.GetColumn(i), ref args);
                }

                private void CellGUI(Rect cellRect, TreeViewItem item, int column, ref RowGUIArgs args)
                {
                    CenterRectUsingSingleLineHeight(ref cellRect);
                    switch (column)
                    {
                        case 0:
                            {
                                var iconRect = new Rect(cellRect.x + 1, cellRect.y + 1, cellRect.height - 2, cellRect.height - 2);
                                if (item.icon != null)
                                {
                                    GUI.DrawTexture(iconRect, item.icon, ScaleMode.ScaleToFit);
                                }
                                DefaultGUI.Label(
                                    new Rect(cellRect.x + iconRect.xMax + 1, cellRect.y, cellRect.width - iconRect.width, cellRect.height),
                                    item.displayName,
                                    args.selected,
                                    args.focused);
                            }
                            break;
                    }
                }

                //=============================================================

                internal static MultiColumnHeaderState CreateDefaultMultiColumnHeaderState()
                {
                    return new MultiColumnHeaderState(GetColumns());
                }

                private static MultiColumnHeaderState.Column[] GetColumns()
                {
                    var retVal = new MultiColumnHeaderState.Column[] {
                            new MultiColumnHeaderState.Column(),
                        };

                    retVal[0].headerContent = new GUIContent("包号列表");
                    retVal[0].minWidth = 180;
                    retVal[0].width = 180;
                    retVal[0].maxWidth = 180;
                    retVal[0].headerTextAlignment = TextAlignment.Left;
                    retVal[0].canSort = false;
                    retVal[0].autoResize = true;

                    return retVal;
                }
            }
        }
    }
}
